package com.cictec.middleware.gps.engine.position;

import java.util.Date;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.DateUtils;
import com.cictec.middleware.commons.utils.gps.GpsUtils;
import com.cictec.middleware.commons.utils.gps.Point;
import com.cictec.middleware.commons.utils.log.MultiLog;
import com.cictec.middleware.commons.utils.log.MultiLogFileNameUtils;
import com.cictec.middleware.commons.utils.log.MultiLogUtils;
import com.cictec.middleware.core.entity.BusLine;
import com.cictec.middleware.core.pojo.MiddlewarePosition;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.BusInstanceEngine;
import com.cictec.middleware.gps.engine.TimeEventBus;
import com.cictec.middleware.gps.engine.TimingPoint;
import com.cictec.middleware.gps.engine.TimingPointEvent;
import com.cictec.middleware.gps.engine.thread.PointExecutorManager;
import com.cictec.middleware.gps.service.BusLineService;
import com.google.common.eventbus.Subscribe;

@Component
public class TerminalPositionListener {
	private static Logger logger = LoggerFactory.getLogger(TerminalPositionListener.class);

	@Autowired
	private TimeEventBus timeEventBus;

	@Autowired
	private BusInstanceEngine busInstanceEngine;
	@Autowired
	private BusLineService busLineService;
	@Autowired
	private TimingPointBuilder bimingPointBuilder;
	@Autowired
	private PointExecutorManager pointExecutorManager;

	@PostConstruct
	public void init() {
		logger.debug("注册【gps位置信息】TerminalPositionListener 到 TimeEventBus");
		timeEventBus.register(this);

	}
	
	@Subscribe
	public void onEventHandler(TerminalPositionEvent event) {
		/*
		 * 通过事件方式调用服务
		 */
		MiddlewarePosition position = event.getPosition();
		onPosition(position);
	}

	/**
	 * GPS位置点分析处理
	 * @param position
	 */
	public void onPosition(MiddlewarePosition position) {
		
		logger.debug("【位置信息事件处理】终端ID {} 原始坐标 {},{}", position.getDevCode(), position.getLat(), position.getLng());
		Point hxPoint = GpsUtils.diqiuToHuoxing(position.getLat(), position.getLng());
		if (hxPoint == null) {
			logger.error("终端ID {} 坐标错误，处理终止。坐标 {},{}", position.getDevCode(), position.getLat(), position.getLng());
			return;
		}
		
		// 根据线路号，查询线路
		BusLine busLine = null;
		try {
			busLine = busLineService.getLineByDeivceLineId(position.getLineId());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("【位置信息事件处理】获取线路信息错误，找不到 终端 {} 所设置的 线路 {} ", position.getDevCode(), position.getLineId());
		}					
		if (busLine == null) {
			logger.warn("【位置信息事件处理】找不到 终端 {} 所设置的 线路 {} ", position.getDevCode(), position.getLineId());
			return;
		}
		
		BusInstance busInstance = busInstanceEngine.getBusInstanceByDevCode(position.getDevCode());
		if(busInstance == null){
			logger.debug("【位置信息事件处理】找不到对应的车辆信息", position.getDevCode(), position.getLat(), position.getLng());
			return;
		}
		// 将数据转换为TimingPoint
		TimingPoint timingPoint = null;
		if(!position.isEnterOut()){
			timingPoint = bimingPointBuilder.builderPosition(position, busLine, hxPoint, busInstance);
			
			String logPath = MultiLogFileNameUtils.getPositionLogName(busLine.getLineName(), position.getDevCode()+"-" + timingPoint.getBusNumber(), DateUtils.formatDate(position.getCreateTime()));
			MultiLog log = MultiLogUtils.getMultiLog(logPath);
			log.debug("lineId:{}, deviceCode:{}, createTime:{}, sendTime:{}", 
					position.getLineId(),
					position.getDevCode(),
					timingPoint.getGatherTime(),
					timingPoint.getUploadTime()
					);
			
			logger.debug("lineId:{}, deviceCode:{}, createTime:{}, sendTime:{}", 
					position.getLineId(),
					position.getDevCode(),
					timingPoint.getGatherTime(),
					timingPoint.getUploadTime()
					);
		}else{
			
			timingPoint = bimingPointBuilder.builderEnterOutPosition(position, busLine, hxPoint, busInstance);
			String logPath = MultiLogFileNameUtils.getPositionEnterOutLogName(busLine.getLineName(), position.getDevCode()+"-" + timingPoint.getBusNumber(), DateUtils.formatDate(position.getCreateTime()));
			MultiLog log = MultiLogUtils.getMultiLog(logPath);
			log.debug("lineId:{}, devCode:{}, 原始站序：{}, enterOut:{}, lineType:{}, stationSeq：{}, stationName:{}, createTime:{}, sendTime:{}", 
					position.getLineId(),
					position.getDevCode(),
					timingPoint.getBusNumber(),
					position.getEnterOutStatus(),
					timingPoint.getLineType(), 
					timingPoint.getStationLineSeqOrg(), 
					timingPoint.getStationNameOrg(),
					timingPoint.getGatherTime(),
					timingPoint.getUploadTime()
					);
			
			logger.debug("lineId:{}, devCode:{}, 原始站序：{}, enterOut:{}, lineType:{}, stationSeq：{}, stationName:{}, createTime:{}, sendTime:{}", 
					position.getLineId(),
					position.getDevCode(),
					timingPoint.getBusNumber(),
					position.getEnterOutStatus(),
					timingPoint.getLineType(), 
					timingPoint.getStationLineSeqOrg(), 
					timingPoint.getStationNameOrg(),
					timingPoint.getGatherTime(),
					timingPoint.getUploadTime()
					);
		}

		timingPoint.setCityCode(position.getCityCode());
		
//		pointExecutorManager.execute(timingPoint);
		TimingPointEvent event = new TimingPointEvent(new Date(), timingPoint);
		timeEventBus.post(event);
	}
	
}
